var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var path = require("path")
var fs = require("fs")
var indexRouter = require('./routes/index');
// var usersRouter = require('./routes/users').default();
var AlipaySdk = require("alipay-sdk").default
var AlipayFormData =require("alipay-sdk/lib/form").default;
var app = express();

// view engine setup
app.engine('.html', require('ejs').__express);
app.set('views', path.join(__dirname, './public/views'));
app.set('view engine', 'html');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/pay',async function(req, res){
  const alipaySdk = new AlipaySdk({
    appId: '2016101600701030',
    privateKey: fs.readFileSync('./public/pem/private-key.pem', 'ascii'),
    gateway: "https://openapi.alipaydev.com/gateway.do"
  });
  const formData = new AlipayFormData();

  formData.addField('notifyUrl', 'http://www.huochaiqi.com/paycallback');
  formData.addField("returnUrl", "http://www.huochaiqi.com/success")
  formData.addField('bizContent', {
    outTradeNo: new Date().valueOf(),
    productCode: "QUICK_WAP_WAY",
    // out_trade_no: 1234567891111111111111111112,
    totalAmount: '88.00',
    subject: '火柴契课程',
    body: '商品详情',
  });

  const result = await alipaySdk.exec(
    'alipay.trade.wap.pay',
    {},
    { formData: formData ,validateSign:true},
  );

  // result 为 form 表单
  res.render("index",{data:result})
});

app.post('/paycallback', async (req, res) => {
  let postData = req.body;
  console.log("触发付款");
  if (postData.trade_status === "TRADE_SUCCESS") {
    // let data = ctx.request.body // 订单信息
  	// ========= 由请求体内的订单信息，在这里进行数据库中订单状态的更改 ============
    console.log("支付完成！");
  }
})
app.use("/success",async (req, res)=>{
  res.json({ok:"支付成功"})
})
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
